package cn.yinuo.website.common.config;

import cn.yinuo.website.common.ResultVO;
import cn.yinuo.website.common.ResultVO.CodeEnum;
import cn.yinuo.website.common.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 * 全局异常处理
 */
@ControllerAdvice(annotations = RestController.class)
public class GlobalExceptionHandler {

	protected static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	@ExceptionHandler(value = Exception.class)
	@ResponseStatus(value = HttpStatus.OK)
	@ResponseBody
	public Object exceptionHandler(HttpServletRequest request, Exception ex) {
		logger.error("请求异常:", ex);
		int code = CodeEnum.ERROR.getCode();
		String message = CodeEnum.ERROR.getDesc();
		// 业务异常处理
		if (ex instanceof BusinessException) {
			code = CodeEnum.BizExcep.getCode();
			message = ((BusinessException) ex).getMessage();
		}
		return new ResultVO<>().setCode( code ).setMsg( message );
	}

	/**
	 * 400 - Bad Request
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(HttpMessageNotReadableException.class)
	public Object handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
		logger.error("参数解析失败", e);
		return new ResultVO<>().setCode(CodeEnum.ERROR.getCode()).setMsg("参数解析失败");
	}

	/**
	 * 405 - Method Not Allowed
	 */
	@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public Object handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
		logger.error("不支持当前请求方法", e);
		return new ResultVO<>().setCode(CodeEnum.ERROR.getCode()).setMsg("不支持当前请求方法");
	}

	/**
	 * 415 - Unsupported Media Type
	 */
	@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
	@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
	public Object handleHttpMediaTypeNotSupportedException(Exception e) {
		logger.error("不支持当前媒体类型", e);
		return new ResultVO<>().setCode(CodeEnum.ERROR.getCode()).setMsg("不支持当前媒体类型");
	}
}
